package org.budo.druid.filter.driver.connect.error;

import java.sql.SQLException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.proxy.jdbc.ConnectionProxy;
import com.alibaba.druid.proxy.jdbc.DataSourceProxy;

/**
 * @author lmw
 */
public class DriverConnectErrorFilter extends FilterEventAdapter {
    private static final Logger log = LoggerFactory.getLogger(DriverConnectErrorFilter.class);

    @Override
    public DruidPooledConnection dataSource_getConnection(FilterChain chain, DruidDataSource dataSource, long maxWaitMillis) throws SQLException {
        try {
            return super.dataSource_getConnection(chain, dataSource, maxWaitMillis);
        } catch (Throwable e) {
            log.error("#27 dataSource_getConnection error, url=" + dataSource.getUrl() + ", rawJdbcUrl=" + dataSource.getRawJdbcUrl(), e);
            throw new SQLException("#28 dataSource_getConnection error, e=" + e, e);
        }
    }

    @Override
    public boolean connection_isReadOnly(FilterChain chain, ConnectionProxy connection) throws SQLException {
        try {
            return super.connection_isReadOnly(chain, connection);
        } catch (SQLException e) {
            DataSourceProxy dataSource = chain.getDataSource();
            log.error("#38 connection_isReadOnly error, url=" + dataSource.getUrl() + ", rawJdbcUrl=" + dataSource.getRawJdbcUrl(), e);
            throw new SQLException("#39 connection_isReadOnly error, e=" + e, e);
        }
    }

    @Override
    public ConnectionProxy connection_connect(FilterChain chain, Properties info) throws SQLException {
        try {
            return super.connection_connect(chain, info);
        } catch (SQLException e) {
            DataSourceProxy dataSource = chain.getDataSource();
            log.error("#49 connection_connect error, properties=" + info + ", url=" + dataSource.getUrl() + ", rawJdbcUrl=" + dataSource.getRawJdbcUrl(), e);
            throw new SQLException("#50 connection_connect error, e=" + e, e);
        }
    }
}